<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="loginname"
            name="用户名"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名', pattern: /\w{6,12}/ }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            登录
          </van-button>
        </div>
        <div style="margin: 16px;">
            <van-button round block type="primary" @click="$router.push('/register')">
                注册
              </van-button>
        </div>
      </van-form>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { Toast } from 'vant'
import { useRouter, type Router } from 'vue-router'
import { loginApi } from '@/api/users'
const loginname = ref<string>('')
const password = ref<string>('')
const $router: Router = useRouter()
const onSubmit = async()=>{
    const res = await loginApi(loginname.value, password.value)
    console.log(res);
    if(((res as unknown) as { code: string }).code === '200'){
        Toast({
      message: '登录成功',
      icon: 'phone-circle-o',
    })

    window.localStorage.setItem('token', res.data.token)
    window.localStorage.setItem('user_id', res.data.userid)
    setTimeout(() => {
      $router.push({ path: '/home' })
    }, 1000)

    return
    }
    
    
}
</script>
<style lang="scss" scoped>
 </style>